package com.zt.securityTest.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zt.securityTest.common.R;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import static com.zt.securityTest.common.ResultCode.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 匿名用户访问无权限资源的处理类
 * 登录时抛出异常的处理类
 * time: 2024.11.26 16.10
 */
@Component
public class AnonymousAuthenticationHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        //设置客户端的响应的内容类型
        response.setContentType("application/json;charset=UTF-8");
        //获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //消除循环引用
        String result = "";
        //数据库中没有此用户,用户名或密码输入错误
        if (authException instanceof BadCredentialsException){
             result = JSON.toJSONString(R.error().code(USERNAME_PWD_ERROR.getCode())
                             .message(USERNAME_PWD_ERROR.getMsg()),
                    SerializerFeature.DisableCircularReferenceDetect);
        //用户名为空
        } else if (authException instanceof InternalAuthenticationServiceException) {
            result = JSON.toJSONString(R.error().code(USERNAME_NULL_ERROR.getCode())
                            .message(USERNAME_NULL_ERROR.getMsg()),
                    SerializerFeature.DisableCircularReferenceDetect);
        //访问没有的资源等
        }else {
            result = JSON.toJSONString(R.error().code(USER_HAS_NO_AUTHORITY.getCode())
                            .message(USER_HAS_NO_AUTHORITY.getMsg()),
                    SerializerFeature.DisableCircularReferenceDetect);
        }

        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
